from pdfminer.high_level import extract_pages
from pdfminer.layout import LTTextContainer
from pypinyin import Style, pinyin
import re, sys

def biaoti_sort(biaoti):
    return pinyin(biaoti[0], errors=lambda x:re.sub('\W','',x), style=Style.TONE3)

def element2col(e):
    for x,c in (920,'c'),(750,'b'),(530,'a'),(320,'c'),(150,'b'),(0,'a'):
        if x < e.x0:
            return c

def fenmu_filter(fenmubiaotis):
    moe = []
    for f in fenmubiaotis:
        if '…' in f['题']: continue
        if re.match('^\d+月$', f['题']): continue
        moe += f,
    return moe

def isfenmubiaoti(e):
    try:
        moe = e._objs[0]._objs[0]
        ret = 1
        ret = ret and 14 == moe.size  # is fenmu size
        ret = ret and 720 > e.y0  # is fenmu pos
    except:
        ret = 0
    return ret

def tiaomu_filter(tiaomubiaotis):
    moe = []
    for t in tiaomubiaotis:
        if '概况' == t['题']: continue
        moe += t,
    return moe

def yelan_concat(yelans):
    return ','.join(f"{a['页']}{a['栏']}"for a in sorted(yelans,key=lambda a:(a['页'],a['栏'])))

fenmubiaotis = []
tiaomubiaotis = []

for page_layout in extract_pages(sys.argv[1]):
    xmid = page_layout.x1 / 2
    _tiaomubiaotis = []
    _fenmubiaotis = []
    for element in page_layout:
        if isinstance(element, LTTextContainer):
            col = element2col(element)
            jiouye = '偶' if element.x0 < xmid else '奇'
            text = element.get_text()
            if moe := re.match('^(?P<页>\d+)\n$', text):
                moed = moe.groupdict()
                ye = int(moed['页'])
                if 1 & ye:
                    jiye = ye
                else:
                    ouye = ye
            elif moe := re.match('【(?P<条目标题>[^】]+)', text):
                moed = moe.groupdict()
                tiaomubiaoti = re.sub('\s', '', moed['条目标题'])
                _tiaomubiaotis += {'奇偶页': jiouye, '栏': col, '题': tiaomubiaoti},
            elif isfenmubiaoti(element):
                fenmubiaoti = re.sub('\s', '', text)
                _fenmubiaotis += {'奇偶页': jiouye, '栏': col, '题': fenmubiaoti},
    for t in _tiaomubiaotis:
        t['页'] = {'奇': jiye, '偶': ouye}[t['奇偶页']]
        del t['奇偶页']
    tiaomubiaotis += _tiaomubiaotis
    try:
        for f in _fenmubiaotis:
            f['页'] = {'奇': jiye, '偶': ouye}[f['奇偶页']]
            del f['奇偶页']
        fenmubiaotis += _fenmubiaotis
    except:
        pass

moe = {}
biaotis = [
        *tiaomu_filter(tiaomubiaotis),
        *fenmu_filter(fenmubiaotis),
        ]
for b in biaotis:
    ti = b['题']
    yelan = {'栏': b['栏'], '页': b['页']}
    if ti in moe:
        moe[ti] += yelan,
    else:
        moe[ti] = [yelan]
moe = sorted(moe.items(), key=biaoti_sort)
moe = [f"{m[0]} {yelan_concat(m[1])}" for m in moe]
moe = '\r\n'.join(moe)
print(moe)
